package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/sms")
public class SmsController {


    @Autowired
    private JedisPool jedisPool;

    @GetMapping("/sendCode/{phone}")
    public Result sendCode(@PathVariable String phone){

        try {
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode4String(6);

            //调用阿里云帮助类发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, phone, code);

            //将验证码存储到redis中（用手机号作为键）,过期时间为5分钟
            jedisPool.getResource().setex(phone + RedisMessageConstant.SENDTYPE_ORDER, 300, code);

            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }catch(Exception ex){
            ex.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }
}
